其他
Fetch API速查表:9个最常见的API请求
为什么要使用Fetch API?
发送简单GET请求
fetch('{url}').then(response => console.log(response));
发送简单POST请求
fetch('{url}', {
method: 'post'
}).then(response => console.log(response));
使用授权令牌进行GET
fetch('{url}', {
headers: {
'Authorization': 'Basic {token}'
}
}).then(response => console.log(response));
使用查询字符串数据进行GET
fetch('{url}?var1=value1&var2=value2')
.then(response => console.log(response));
使用CORS进行GET
fetch('{url}', {
mode: 'cors'
}).then(response => console.log(response));
使用授权令牌和查询字符串数据进行POST
fetch('{url}?var1=value1&var2=value2', {
method: 'post',
headers: {
'Authorization': 'Bearer {token}'
}
}).then(response => console.log(response));
使用表单数据进行POST
let formData = new FormData();
formData.append('field1', 'value1');
formData.append('field2', 'value2');
fetch('{url}', {
method: 'post',
body: formData
}).then(response => console.log(response));
使用JSON数据进行POST
fetch('{url}', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'field1': 'value1',
'field2': 'value2'
})
})
.then(response => console.log(response));
使用JSON数据和CORS进行POST
fetch('{url}', {
method: 'post',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'field1': 'value1',
'field2': 'value2'
})
})
.then(response => console.log(response));
如何处理Fetch API请求的结果
.then()
和回调函数来处理响应的原因:fetch(...).then(response => {
// process the response
}
但是,如果您处于异步函数中,也可以等待结果:
async function getData(){
let data = await fetch(...);
// process the response
}
现在让我们看一下如何从响应中提取数据:
如何检查Fetch API响应的状态码
发送POST,PATCH和PUT请求时,我们通常对返回状态代码感兴趣:
fetch(...).then(response => {
if (response.status == 200){
// all OK
} else {
console.log(response.statusText);
}
});
如何获取Fetch API响应的简单值
某些API端点可能会发回使用您的数据创建的新数据库记录的标识符:
var userId;
fetch(...)
.then(response => response.text())
.then(id => {
userId = id;
console.log(userId)
});
如何转换Fetch API响应的JSON数据
但是在大多数情况下,您会在响应正文中接收JSON数据:
var dataObj;
fetch(...)
.then(response => response.json())
.then(data => {
dataObj = data;
console.log(dataObj)
});
async function getData(){
var dataObj;
const response = await fetch(...);
const data = await response.json();
dataObj = data;
console.log(dataObj);
}
总结
原文:https://www.freecodecamp.org/news/fetch-api-cheatsheet/
作者:Ondrej Polesny
粉丝福利
132期留言+在看幸运用户:晨晨虎,速找我领取红包。
临走前留下,今天的福利
福利1:《Vue3.0+TS仿知乎专栏》获取资源请在公众号对话框中回复关键字:006,如果没有关注请扫下面的二维码 福利2:在看+留言,我随机抽取一位认真留言的小伙伴,给他发一个5~10不等的红包奖励
推荐阅读
- END -
点赞 + 在看 + 留言,下一个幸运儿就是你!
走心的分享更容易被抽中~
开奖时间 下期文末